<template>
  <div class="mocks-container">
    <mocks-header ref="header"
                  v-show="showHeader"
                  @nextClick="handleNextBtnClick"
                  @timeOver="handleTimeOver"
                  :test-time="testTime"
                  :name="paperName"></mocks-header>
    <!--主体-->
    <div class="mocks-main">
      <router-view ref="router" />
    </div>
    <!--底部-->
    <div class="mocks-footer"></div>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex';
  import MocksHeader from './components/header';

  //配置弹窗全局样式（放哪？）
  layer.config({
    extend: 'mocksSkin/style.css',
    skin: 'layer-ext-moon'
  });

  export default {
    name: 'App',
    components: { MocksHeader },
    data () {
      return {
        paperType: '',
        showHeader: true
      };
    },
    created () {
      let paperId = this.$route.params.paperId;
      let courseId = this.$route.params.courseId;
      this.paperType = this.$route.params.paperType;
      if (paperId) {
        this.updatePaperId(paperId);
        this.updateCourseId(courseId);
        let routerName = this.$route.name;
        if (routerName == 'home') {
          this._getResult(paperId);
        } else {
          this._getPaperInfo();
        }
      }
      this.showHeader = !(this.$route.name === '404');
    },
    watch: {
      '$route.name' (val) {
        this.showHeader = !(val === '404');
      },
      'mocksStatus' (val) {
        if (val == 'start') {
          this._startMocks();
        }
      }
    },
    computed: {
      ...mapState([
        'mocksStatus',
        'paperInfo',
        'totalPart',
        'currentPart',
        'totalScore',
        'testTime',
        'paperId',
        'courseId',
        'partInfo',
        'showHeaderPart'
      ]),
      paperName () {
        if (this.paperInfo) {
          return this.paperInfo.paper_name;
        }
        return '';
      }
    },
    methods: {
      ...mapActions([
        'updatePaperId',
        'updateCourseId',
        'updatePaperInfo',
        'updateCurrentPart',
        'updateShowHeaderPart',
        'updateDisabledNextBtn'
      ]),
      _checkRouter () {
        let routerName = this.$route.name;
        if (routerName === 'MocksIllustration' || routerName === 'MocksQuestion' || routerName === 'MocksSpeakQuestion') {
          this._startMocks();
        }
      },
      _getResult () {
        let _this = this;
        $.ajax({
          url: 'http://www.ruixinnj.com/report/get_status',
          // url: '/api/mocks/result',
          data: {
            paperId: this.paperId,
            courseId: this.courseId,
            paperType: this.paperType,
            random_string: (typeof random_string == 'string' ? random_string : ''),
            secret_string: (typeof secret_string == 'string' ? secret_string : '')
          },
          type: 'post',
          dataType: 'json',
          success: function (response) {
            if(response.status == 1) {
              let data  = response.data;
              if (data.result == 0) {
                _this._getPaperInfo();
                //paperType:2为口语录音
                if (_this.paperType == 2) {
                  _this.$router.replace(`/test-video/${_this.paperId}/${_this.courseId}`);
                } else {
                  _this.$router.replace(`/start/${_this.paperId}/${_this.courseId}`);
                }
              } else {
                _this.$router.replace(`/result/${_this.paperId}/${data.result}/${data.score}`);
              }
            } else {
              layer.msg(response.msg);
            }
          }
        });
      },
      _getPaperInfo () {
        let _this = this;
        $.ajax({
          url: 'http://www.ruixinnj.com/test/get_paper',
          // url: '/api/mocks/paper',
          type: 'post',
          data: {
            id: _this.paperId,
            random_string: (typeof random_string == 'string' ? random_string : ''),
            secret_string: (typeof secret_string == 'string' ? secret_string : '')
          },
          dataType: 'json',
          success: function (response) {
            if (response.status == 1) {
              _this.updatePaperInfo(response.data);
              _this._checkRouter();
            } else {
              layer.msg(response.msg);
            }
          }
        })
      },
      _startMocks () {
        this.updateShowHeaderPart(true);
        this.updateDisabledNextBtn(false);
        let $header = this.$refs['header'];
        if ($header) {
          $header.startMocks();
        }
      },
      _submitAnswerSuccess () {
        let currentPart = this.currentPart;
        if (++currentPart <= this.totalPart) {
          this.updateCurrentPart(currentPart);
          let _path = `/illustration/${this.paperId}/${this.courseId}/${this.currentPart}`;
          this.$router.push(_path);
        }
      },
      //next按钮 next或者submit
      handleNextBtnClick () {
        let routerName = this.$route.name;
        if (routerName === 'MocksIllustration') {
          let _path = '';
          if (this.partInfo && this.partInfo.part_type == 2) {
            _path = `/speak/${this.paperId}/${this.courseId}/${this.currentPart}/1`
          } else {
            _path = `/question/${this.paperId}/${this.courseId}/${this.currentPart}`;
          }
          this.$router.push(_path);
        } else if (routerName === 'MocksQuestion') {
          let $router = this.$refs['router'];
          if ($router && $router.$options.componentName === 'MocksQuestion') {
            let submitPaper = (this.currentPart == this.totalPart);
            $router.submitAnswer(this._submitAnswerSuccess, submitPaper);
          }
        } else if (routerName === 'MocksSpeakQuestion'){
          let $router = this.$refs['router'];
          if ($router && $router.$options.componentName === 'MocksSpeakQuestion') {
            let submitPaper = (this.currentPart == this.totalPart);
            $router.submitAnswer(this._submitAnswerSuccess, submitPaper);
          }
        }
      },
      handleTimeOver () {
        let _this = this;
        let routerName = this.$route.name;
        let $router = this.$refs['router'];
        if (routerName == 'MocksSpeakQuestion' || routerName == 'MocksIllustration') {
          layer.alert('<img src="/paper/images/dialog_bg.png" style="margin-bottom: 15px" alt="">' +
            '<p>倒计时结束，请提交试卷</p>', {title: false, closeBtn: 0}, (index) => {
            $router.submitPaper();
            layer.close(index);
          });
        }
        else if(routerName == 'MocksQuestion'){
          $router.submitEndAnswer();
        }
      }
      // handleTimeOver () {
      //   let _this = this;
      //   let routerName = this.$route.name;
      //   if (routerName == 'MocksIllustration' || routerName == 'MocksQuestion' || 'MocksSpeakQuestion') {
      //     let $router = this.$refs['router'];
      //     if ($router) {
      //       layer.alert('<img src="/paper/images/dialog_bg.png" alt="">' +
      //         '<p>确认要提交试卷吗？</p>', {title: false, closeBtn: 0}, (index) => {
      //         $router.submitPaper();
      //         layer.close(index);
      //       });
      //       // $router.submitPaper();
      //     }
      //   }
      // }
    }
  }
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}
</style>
